package com.py.framework.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.py.framework.core.common.Page;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.entity.WorkFlowBus;
import com.py.framework.entity.WorkFlowWrapper;
import com.py.framework.service.ActHistoryService;
import com.py.framework.service.WorkFlowService;

/**
 * 流程历史Services实现
 * 
 * @author Leegern
 * @date 2018年5月23日
 */
@Service
public class ActHistoryServiceImpl implements ActHistoryService {

	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private WorkFlowService workflowService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.py.framework.service.ActHistoryService#queryActHistoryDataList(com.jd
	 * .framework.core.common.Page)
	 */
	@Override
	public List<WorkFlowWrapper> queryActHistoryDataList(Page page, long userId, String startTime, String endTime, String processName) {
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
		List<WorkFlowWrapper> list = new ArrayList<WorkFlowWrapper>();
		WorkFlowWrapper wrapper = null;
		WorkFlowBus workflow = null;
		String currUserId = String.valueOf(userId);
		int firstResult = (page.getCurrentPage() - 1) * page.getPageSize(), maxResults = page.getPageSize();
		int totalCount = 0;
		try {
			HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().taskAssignee(currUserId);

			//加日期和流程名称字段查询
			if(null!=processName && !processName.trim().equals("")){
				query.processDefinitionNameLike(processName);
			}

			if(null!=startTime && !startTime.trim().equals("")){
				try {
					query.taskCreatedAfter(format.parse(startTime));
				} catch (ParseException e) {
					ExceptionLogger.error(e);
				}
			}

			if(null!=endTime && !endTime.trim().equals("")){
				try {
					query.taskCreatedBefore(format.parse(endTime));
				} catch (ParseException e) {
					ExceptionLogger.error(e);
				}
			}

			query.orderByHistoricTaskInstanceEndTime().desc();

			totalCount = (int) query.count();
			List<HistoricTaskInstance> historicTaskInstances = query.listPage(firstResult, maxResults);
			for (HistoricTaskInstance historicTask : historicTaskInstances) {
				String procId = historicTask.getProcessInstanceId();
				// 获取页面要展示的业务数据
				workflow = workflowService.findActByProcId(procId);
				wrapper = new WorkFlowWrapper();
				if (workflow != null) {
					BeanUtils.copyProperties(workflow, wrapper);

				}
				ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
						.processDefinitionId(historicTask.getProcessDefinitionId()).singleResult();

				// 需要展示的数据
				wrapper.setProcessDefinitionName(processDefinition.getName());
				wrapper.setTaskName(historicTask.getName());
				wrapper.setTaskStartTime(historicTask.getStartTime());
				wrapper.setTaskEndTime(historicTask.getEndTime());

				list.add(wrapper);
			}
		} catch (Exception e) {
			ExceptionLogger.error(e);
		}
		page.setTotalCount(totalCount);
		return list;
	}
}